package com.weihong.demo.trade;

import com.futu.openapi.FTAPI_Conn;
import com.futu.openapi.FTAPI_Conn_Trd;
import com.futu.openapi.FTSPI_Conn;
import com.futu.openapi.FTSPI_Trd;
import com.futu.openapi.pb.TrdCommon;
import com.futu.openapi.pb.TrdGetOrderList;
import com.weihong.demo.evn.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class OrderListService implements FTSPI_Conn, FTSPI_Trd {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final FTAPI_Conn_Trd trd = new FTAPI_Conn_Trd();
    public volatile boolean isConnected = false;
    public volatile boolean isResponse = false;
    public volatile TrdGetOrderList.S2C s2C;

    public TrdGetOrderList.S2C getOrderList(int trdEnv, long trdAcc) {
        init();
        s2C = null;
        isResponse = false;

        TrdCommon.TrdHeader header = TrdCommon.TrdHeader.newBuilder()
                .setAccID(trdAcc)
                .setTrdEnv(trdEnv)
                .setTrdMarket(TrdCommon.TrdMarket.TrdMarket_HK_VALUE)
                .build();

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime beginTime = now.minusMinutes(7);
        LocalDateTime endTime = now.minusMinutes(5);
        TrdCommon.TrdFilterConditions trdFilterConditions = TrdCommon.TrdFilterConditions.newBuilder()
                .setBeginTime(beginTime.format(Config.futuTime))
                .setEndTime(endTime.format(Config.futuTime)).build();

        TrdGetOrderList.C2S c2s = TrdGetOrderList.C2S.newBuilder()
                .setHeader(header)
                .setFilterConditions(trdFilterConditions)
                .addFilterStatusList(TrdCommon.OrderStatus.OrderStatus_Filled_All_VALUE)
                .addFilterStatusList(TrdCommon.OrderStatus.OrderStatus_Filled_Part_VALUE)
                .setRefreshCache(true)
                .build();

        trd.getOrderList(TrdGetOrderList.Request.newBuilder().setC2S(c2s).build());

        while (!isResponse){
            logger.info("waiting for getOrderList");
            Config.sleepsec(1);
        }
        return s2C;
    }

    private void init() {
        if (isConnected) {
            return;
        }

        synchronized (OrderListService.class) {
            if (isConnected) {
                return;
            }

            trd.setClientInfo("OrderListService", 3);  //设置客户端信息
            trd.setConnSpi(this);  //设置连接相关回调
            trd.setTrdSpi(this);   //设置交易相关回调
            trd.initConnect(Config.opendIP, (short) Config.opendPort, false);
            while (!isConnected) {
                logger.info("waiting for connect of OrderListService");
                Config.sleepsec(1);
            }
        }
    }

    @Override
    public void onInitConnect(FTAPI_Conn client, long errCode, String desc) {
        if (errCode != 0) {
            logger.error("Trd onInitConnect: ret={} desc={} connID={}", errCode, desc, client.getConnectID());
            System.exit(-1);
        } else {
            isConnected = true;
        }
    }

    @Override
    public void onReply_GetOrderList(FTAPI_Conn client, int nSerialNo, TrdGetOrderList.Response rsp) {
        if (rsp.getRetType() != 0) {
            logger.error("TrdGetOrderList failed: {}", rsp.getRetMsg());
            System.exit(-1);
        } else {
            logger.info("TrdGetOrderList done");
            s2C = rsp.getS2C();
        }

        isResponse = true;
    }
}
